{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "cosθ=a·b/|a|*|b|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.8528028654224417\n"
     ]
    }
   ],
   "source": [
    "from sklearn.feature_extraction.text import CountVectorizer\n",
    "import numpy as np\n",
    "from scipy.linalg import norm\n",
    "\n",
    "def tf_similarity(str1, str2):\n",
    "    def add_space(str):\n",
    "        return ' '.join(list(str))\n",
    "    \n",
    "    # 将字中间加入空格\n",
    "    str1, str2 = add_space(str1), add_space(str2)\n",
    "    # 转化为TF矩阵\n",
    "    cv = CountVectorizer(tokenizer=lambda str: str.split())\n",
    "    corpus = [str1, str2]\n",
    "    vectors = cv.fit_transform(corpus).toarray()\n",
    "    # 计算TF系数\n",
    "    return np.dot(vectors[0], vectors[1]) / (norm(vectors[0]) * norm(vectors[1]))   \n",
    "\n",
    "\n",
    "str1 = '今天学习了自然语言处理'\n",
    "str2 = '今天学习语言处理'\n",
    "print(tf_similarity(str1, str2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
